require 'hpricot'

class Currency < ActiveRecord::Base
	validates_numericality_of :usd, :eur, :rub
	
	cattr_accessor :parce_url, :value
	@@parce_url = Settings.config.currency_url
	
	def self.today
		@@value = find(:first, :conditions=>['DATE(created_at) = ?', Date.today]) if @@value.blank? || @@value.created_at.to_date < Date.today
		return parse if @@value.blank?
		@@value
	end
	
	def self.parse
		c = self.new
		page = Hpricot(get_file(@@parce_url))
		table = page.search("//table[@class='full']").first
		return self.first if table.nil?
		#date = page.search("//div[@class='date']").first
		table.search("/tr").each do |tr|
			tds = tr.search("/td")
			next if tds.size < 7
			number = tds[4].inner_text.to_f / tds[2].inner_text.to_f
			case tds[1].inner_text.strip.downcase
				when 'usd'
					c.usd = number
				when 'rub'
					c.rub = number
				when 'eur'
					c.eur = number
			end
		end
		c.save!
		c
	end
	
	private
	
	def self.get_file(url)
    IO.popen("wget -U \"Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12\" -t 4 -O- \"#{url}\"").read
  end
end
